package org.ehe.business.overdue.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import org.ehe.business.overdue.domain.OverdueRecord;
import org.ehe.business.overdue.domain.OverdueRecordHistory;
import org.ehe.business.overdue.domain.bo.OverdueRecordBo;
import org.ehe.business.overdue.domain.vo.OverdueRecordVo;
import org.ehe.common.mybatis.core.mapper.BaseMapperPlus;

import java.util.List;

/**
 * @author :zhangnn
 * @className :OverdueRecordMapper
 * @description: TODO
 * @date 2025-07-29 15:29:13
 */

public interface OverdueRecordMapper extends BaseMapperPlus<OverdueRecord, OverdueRecordVo> {
    /**
     * 插入或更新记录
     *
     * @return
     */
    default boolean insertOrUpdate(OverdueRecord record) {
        // 先尝试查询是否存在
        OverdueRecord existing = this.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OverdueRecord>()
                .eq("biz_type", record.getBizType())
                .eq("biz_id", record.getBizId())
        );

        if (existing != null) {
            // 更新现有记录
            record.setId(existing.getId());
            this.updateById(record);
        } else {
            // 插入新记录
            this.insert(record);
        }
        return false;
    }

    /**
     * 更新处理状态
     */
    @Update("UPDATE t_overdue_record SET handle_status = #{handleStatus}, update_time = NOW() " +
        "WHERE biz_type = #{bizType} AND biz_id = #{bizId}")
    int updateHandleStatus(@Param("bizType") String bizType,
                           @Param("bizId") Long bizId,
                           @Param("handleStatus") Integer handleStatus);

    @Select("SELECT * FROM t_overdue_record" +
        "    WHERE biz_type = #{bizType}" +
        "      AND biz_id = #{bizId}" +
        "      AND del_flag = '0' " +
        "     order by deadline_time desc limit 1")
    OverdueRecord selectByBizTypeAndId(@Param("bizType") String bizType,
                                       @Param("bizId") Long bizId);


    @Insert("INSERT INTO t_overdue_record_history (" +
        "  overdue_id, " +
        "  deadline_time, " +
        "  tenant_id " +
        ") VALUES (" +
        "  #{overdue.id}, " +
        "  NOW(), " +
        "  #{overdue.tenantId} " +
        ")")
    void insertHistory(@Param("overdue") OverdueRecord overdue);


    @Select("SELECT * FROM t_overdue_record_history" +
        "    WHERE overdue_id = #{overdueId}")
    List<OverdueRecordHistory> queryOverdueHistory(@Param("overdueId") Long id);
}
